package com.gu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gu.VO.ServerResponse;
import com.gu.dao.VehicleRefuelingInfoDao;
import com.gu.entity.Setting;
import com.gu.entity.VehicleRefuelingInfo;
import com.gu.entity.excelExportEntity.VehicleRefuelingInfoExp;
import com.gu.enumeration.vehicleTypeEnum.VehicleTypeEnum;
import com.gu.service.SettingService;
import com.gu.service.VehicleRefuelingInfoService;
import com.gu.service.VehicleRefuelingRuleService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: gusongliao
 * @Description: 车辆加油信息服务实现类
 * @createDate 2023/01/05 22:05
 */
@Service
public class VehicleRefuelingInfoServiceImpl implements VehicleRefuelingInfoService {
    private final static Logger LOGGER = Logger.getLogger(VehicleRefuelingInfoServiceImpl.class);

    @Autowired
    private SettingService settingService;

    @Autowired
    private VehicleRefuelingInfoDao vehicleRefuelingInfoDao;

    @Autowired
    private VehicleRefuelingRuleService vehicleRefuelingRuleService;


    @Override
    public ServerResponse importFile(MultipartFile[] file) throws IOException {
        if (file == null || file.length == 0) {
            return ServerResponse.error(400, "无文件信息");
        }
        List<String> pathList = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            try {
                List<String> inputIds = vehicleRefuelingInfoDao.selectAllInputId();
                List<String> importedInputIds = new ArrayList<>();
                LOGGER.info("开始解析excel数据");
                EasyExcel.read(multipartFile.getInputStream(), VehicleRefuelingInfo.class, new ReadListener() {

                    @Override
                    public void invoke(Object o, AnalysisContext analysisContext) {
                        try {
                            VehicleRefuelingInfo vehicleRefuelingInfo = (VehicleRefuelingInfo) o;
                            String inputId = vehicleRefuelingInfo.getInputid();
                            if (!importedInputIds.contains(inputId)) {
                                vehicleRefuelingInfo.setUpdatetimestamp(new Date());
                                vehicleRefuelingInfo.setSuspectedErrorFlag(0);
                                vehicleRefuelingRuleService.checkRule(vehicleRefuelingInfo);
                                // 单价和升数不为空，且都不为0
                                BigDecimal fuelLiters = vehicleRefuelingInfo.getFuelliters();
                                BigDecimal fuelUnitPrice = vehicleRefuelingInfo.getFuelunitprice();
                                if (fuelLiters != null && fuelUnitPrice != null
                                        && fuelLiters.compareTo(BigDecimal.ZERO) != 0
                                        && fuelUnitPrice.compareTo(BigDecimal.ZERO) != 0
                                ) {
                                    vehicleRefuelingInfo.setFueltotalprice(fuelLiters.multiply(fuelUnitPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                                if (inputId != null && !"".equals(inputId)) {
                                    if (inputIds.contains(inputId)) {
                                        VehicleRefuelingInfo vehicleRefuelingInfoOld = vehicleRefuelingInfoDao.selectByInputId(inputId);
                                        vehicleRefuelingInfo.setId(vehicleRefuelingInfoOld.getId());
                                        vehicleRefuelingInfoDao.updateByPrimaryKey(vehicleRefuelingInfo);
                                    } else {
                                        vehicleRefuelingInfo.setCreatetimestamp(new Date());
                                        insertSelective(vehicleRefuelingInfo);
                                    }
                                    importedInputIds.add(inputId);
                                }
                            }
                        } catch (Exception e) {
                            LOGGER.error(e);
                            throw e;
                        }
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                    }
                }).sheet().doRead();
            } catch (Exception e) {
                LOGGER.error(e);
                e.printStackTrace();
                return ServerResponse.error(500, "导入文件异常");
            }
        }
        return ServerResponse.success(pathList);
    }

    @Override
    public ServerResponse exportFile(String vehicleSelectorParam
            , String submitTimeStart
            , String submitTimeEnd
            , String createTimeStart
            , String createTimeEnd
            , Integer matchRule
            ) {
        List<VehicleTypeEnum> vehicleTypeEnum = VehicleTypeEnum.getVehicleTypeEnum();
        for (VehicleTypeEnum typeEnum : vehicleTypeEnum) {
            try {
                exportExcel(vehicleSelectorParam, submitTimeStart, submitTimeEnd, createTimeStart, createTimeEnd, typeEnum, matchRule);
            } catch (Exception e) {
                LOGGER.error("导出文件失败!!!", e);
                e.printStackTrace();
                return ServerResponse.error(500, "导出文件失败!!!");
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
        Setting setting = settingService.selectSettingByModuleAndName("VEHICLE", "REFUELING_EXPORT_PATH");
        String exportPath = "D:\\vehicleRefuelingInfo";
        if (setting != null && !"".equals(setting.getValue())) {
            exportPath = setting.getValue();
        }
        exportPath += "\\" + sdf.format(new Date());
        return ServerResponse.success(200,"文件导出成功，请查看文件夹<br>" + exportPath + "<br>中数据");
    }

    public void exportExcel(String vehicleSelectorParam
            , String submitTimeStart
            , String submitTimeEnd
            , String createTimeStart
            , String createTimeEnd
            , VehicleTypeEnum vehicleType
            , Integer matchRule
    ) throws IOException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Setting setting = settingService.selectSettingByModuleAndName("VEHICLE", "REFUELING_EXPORT_PATH");
        String exportPath = "D:\\vehicleRefuelingInfo";
        if (setting != null && !"".equals(setting.getValue())) {
            exportPath = setting.getValue();
        }
        exportPath += "\\" + sdf.format(new Date());
        File file = new File(exportPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String exportExcelName = vehicleType.getVehicleType() + "数据报表.xlsx";

        File fileExcel = new File(exportPath + "\\" + exportExcelName);
        if (!fileExcel.exists()) {
            fileExcel.createNewFile();
        }

        // 根据哪个模板进行填充
        ClassPathResource classPathResource = new
                ClassPathResource("excelTemplate/vehicle_info_template.xlsx");

        InputStream inputStream = classPathResource.getInputStream();

        // 浏览器下载
//        BufferedOutputStream bos = new BufferedOutputStream(fos);
//        OutputStream out = response.getOutputStream();
//        BufferedOutputStream bos = new BufferedOutputStream(out);
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        //导出的文件名
//        String fileName = URLEncoder.encode(exportExcelName, "utf-8");
//        response.setHeader("Content-disposition", "attachment; filename=" + new
//                String(fileName.getBytes("UTF-8"), "ISO-8859-1"));


        //list每一条数据都新创建一行
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//            {xxx}代表map填充(填入key)或者bean填充(填入属性名)
//            {.xxx}代表list填充,填入对应属性名（前面有一个点）
//            {xxx}代表map填充 （前面没点）
        ExcelWriter excelWriter = EasyExcel.write(fileExcel).withTemplate(inputStream).build();

        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        //获得的数据
        List<VehicleRefuelingInfoExp> vehicleRefuelingInfoExps = vehicleRefuelingInfoDao.selectSummaryDataByParam(vehicleSelectorParam, submitTimeStart, submitTimeEnd, createTimeStart, createTimeEnd, vehicleType, matchRule);

        BigDecimal avgFuelUnitPrice = new BigDecimal("0.00");
        BigDecimal sumFuelLiters = new BigDecimal("0.00");
        BigDecimal sumFuelTotalPrice = new BigDecimal("0.00");
//        {avgFuelUnitPrice}	{sumFuelLiters}	{sumFuelTotalPrice}
        if (vehicleRefuelingInfoExps != null && vehicleRefuelingInfoExps.size() > 0) {
            BigDecimal size = new BigDecimal(vehicleRefuelingInfoExps.size());
            for (VehicleRefuelingInfoExp vehicleRefuelingInfoExp : vehicleRefuelingInfoExps) {
                BigDecimal fuelLiters = vehicleRefuelingInfoExp.getFuelLiters();
                BigDecimal fuelTotalPrice = vehicleRefuelingInfoExp.getFuelTotalPrice();
                sumFuelLiters = sumFuelLiters.add(fuelLiters == null ? BigDecimal.ZERO : fuelLiters);
                sumFuelTotalPrice = sumFuelTotalPrice.add(fuelTotalPrice == null ? BigDecimal.ZERO : fuelTotalPrice);
            }
            avgFuelUnitPrice = sumFuelTotalPrice.divide(sumFuelLiters,2,BigDecimal.ROUND_HALF_UP);
        }
        Map<String,Object> summaryData = new HashMap<>();
        summaryData.put("avgFuelUnitPrice",avgFuelUnitPrice);
        summaryData.put("sumFuelLiters",sumFuelLiters.setScale(2,BigDecimal.ROUND_HALF_UP));
        summaryData.put("sumFuelTotalPrice",sumFuelTotalPrice.setScale(2,BigDecimal.ROUND_HALF_UP));
        summaryData.put("nowDate",sdf1.format(new Date()));

        //list map 是查询并需导出的数据，并且里面的字段和excel需要导出的字段对应
        excelWriter.fill(summaryData, fillConfig, writeSheet);
        excelWriter.fill(vehicleRefuelingInfoExps, fillConfig, writeSheet);
        excelWriter.finish();
//        excelWriter.
//        bos.write();
//        bos.flush();
    }

    @Override
    public int insertSelective(VehicleRefuelingInfo record) {
        return vehicleRefuelingInfoDao.insertSelective(record);
    }

    @Override
    public PageInfo getAllVehicleRefuelingInfo(Integer pageNum, Integer pageSize, String vehicleSelectorParam, String submitTimeStart
            , String submitTimeEnd
            , String createTimeStart
            , String createTimeEnd
            , Integer matchRule
    ) {
        PageHelper.startPage(pageNum, pageSize);
        List<VehicleRefuelingInfo> userDOList = vehicleRefuelingInfoDao.getAllVehicleRefuelingInfo(vehicleSelectorParam, submitTimeStart, submitTimeEnd, createTimeStart, createTimeEnd,matchRule);
        PageInfo pageInfo = PageInfo.of(userDOList);
        return pageInfo;
    }


    @Override
    public ServerResponse delete(String dataIds) {
        if ("[]".equals(dataIds)) {
            return ServerResponse.error(-1, "删除失败！！！未发现要删除的数据");
        }
        dataIds = dataIds.replaceAll("\\[", "").replaceAll("]", "");
        String[] ids = dataIds.split(",");
        try {
            vehicleRefuelingInfoDao.delete(ids);
        } catch (Exception e) {
            LOGGER.error(e);
            return ServerResponse.error(-1, "删除失败！！！未发现要删除的数据");
        }
        return ServerResponse.SUCCESS;
    }

    public String getSuffix(MultipartFile multipartFile) {
        String fileSuffixName = multipartFile.getOriginalFilename();
        String fileSuffix = fileSuffixName.substring(fileSuffixName.lastIndexOf("."));
        return fileSuffix;
    }

}
